<?php

namespace Jammiest\SwigeCore\Tools;

use ReflectionClass;

class Path
{
    public static function getPathByNamespace($namespace)
    {
        $loaders = \Composer\Autoload\ClassLoader::getRegisteredLoaders();
        if (count($loaders) === 0) {
            throw new \RuntimeException("Unable to retrieve the Composer autoloader instance.");
        } else if(count($loaders) > 1) {
            throw new \RuntimeException("Multiple Composer autoloader instances detected. Unable to determine which one to use.");
        }
        $prefixesPsr4 = $loaders[array_key_first($loaders)]->getPrefixesPsr4();
        
        foreach ($prefixesPsr4 as $prefix => $paths) {
            if (str_starts_with($namespace, rtrim($prefix, '\\'))) {
                // 找到匹配的命名空间前缀
                $relativeNamespace = substr($namespace, strlen(rtrim($prefix, '\\')));
                $relativePath = str_replace('\\', DIRECTORY_SEPARATOR, $relativeNamespace);
                // 返回第一个路径加上相对路径
                return rtrim($paths[0], DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $relativePath;
            }
        }
        throw new \InvalidArgumentException("Unable to locate the path based on the namespace:$namespace");
    }

    /**
     * 获取App基本路径
     *
     * @param string $path
     * @return string
     */
    public static function getBasePath(string $path = ''): string
    {
        // 尝试通过 Composer 自动加载器获取项目根目录
        $reflection = new ReflectionClass(\Composer\Autoload\ClassLoader::class);
        $vendorDir = dirname($reflection->getFileName(), 2);
        return dirname($vendorDir) . ($path ? DIRECTORY_SEPARATOR . ltrim($path, DIRECTORY_SEPARATOR) : $path);
    }
}
